import { Button } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { ParamsType, ProTable, ProTableProps } from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import { getTableScroll } from '@/util/table';

let flag = true;

type MyProTableProps<DataType, Params> = {
  isAdd?: boolean;
  clickAdd?: () => void;
  x?: string | number | true | 'max-content';
} & ProTableProps<DataType, Params>;

const MyScrollTable = <DataType extends Record<string, any>, Params extends ParamsType>({
  isAdd,
  clickAdd,
  toolBarRender,
  x = true,
  ...restProps
}: MyProTableProps<DataType, Params>) => {
  // 切换页面时更新key值，强制ProTable重新渲染
  const [scrollY, setScrollY] = useState<number | undefined>(0);
  const actionRef = useRef(null);
  const isMounted = useRef(false);
  let timer: NodeJS.Timeout;
  // let extraHeight: number;

  // if (restProps.pagination === false) {
  //   extraHeight = 0;
  // }

  const setHeight = (height = scrollY || 0) => {
    const table = document.querySelector('.ant-table-container .ant-table-tbody');
    if (table) {
      const cHeight = table.getBoundingClientRect().height;
      // console.log('setScrollY', height, cHeight)
      if (height !== undefined && height >= cHeight) {
        setScrollY(undefined);
      }
    }
  };
  const changSize = (n = 0) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      if (isMounted.current) {
        const height = getTableScroll();
        setScrollY(height);
        setHeight(height);
      }
    }, n);
  };
  window.addEventListener('resize', () => {
    if (actionRef) changSize();
  });
  const onLoad = () => {
    changSize();
    if (flag) {
      flag = false;
    }
  };
  //页面加载完成后才能获取到对应的元素及其位置
  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
      if (timer) clearTimeout(timer);
      window.removeEventListener('resize', () => {});
    };
    //展开所有行
  }, []);
  return (
    <ProTable<DataType, Params>
      actionRef={actionRef}
      headerTitle="列表"
      rowKey="id"
      onLoad={onLoad}
      toolBarRender={(action, rows) => [
        typeof toolBarRender === 'function' && toolBarRender(action, rows),
        isAdd !== false && (
          <Button type="primary" key="primary" onClick={clickAdd}>
            <PlusOutlined /> 新增
          </Button>
        ),
      ]}
      {...restProps}
      scroll={{
        y: scrollY,
        x,
      }}
      form={{
        ...restProps?.form,
        onCollapse: () => {
          setScrollY(getTableScroll());
        },
      }}
    />
  );
};

export default MyScrollTable;
